<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 质量奖惩管理 -->
    <div id="base-breadcrumb" style="position: relative; overflow: hidden">
      <!-- 搜索 -->
      <searchData
        ref="searchData"
        :searchData="searchArr"
        :range.sync="form"
        @search="search"
        @reset="handleReset"
      ></searchData>

      <a-card :bordered="false">
        <!-- <title-name :title="$route.meta.title"></title-name> -->
        <list-table
          ref="table"
          row-key="id"
          :columns="columns"
          :request="loadData"
          :select-config="{ use: true, type: 'checkbox', rowKey: 'id' }"
          :export-config="{
            use: true,
            select: '质量奖罚管理选中',
            all: '质量奖罚管理全部',
            customColumns: customColumns
          }"
          :isShowCountBar="false"
          @select-click="selectClick"
        >
          <template slot="searchQuery" slot-scope="text, record">
              {{ record.branchCompanyName || '' }}{{ record.projectName ? '-' + record.projectName : '' }}
          </template>
          <span v-if="!record.isChildren" slot="action" slot-scope="text, record">
            <MoreButton>
              <a v-btnPermission="[
                      {
                        ident: 'prma_seex',
                        code: 'seex_qm_006_loo_04'
                      },
                      {
                        ident: 'prma_buco',
                        code: 'buco_qm_006_loo_04'
                      }
              ]" @click="handleManage(2, record)">查看</a>
              <template v-if="record.isOperation && (record.statusCode === '0' || record.statusCode === '3')">
                <a v-btnPermission="[
                      {
                        ident: 'prma_seex',
                        code: 'seex_qm_006_edi_02'
                      },
                      {
                        ident: 'prma_buco',
                        code: 'buco_qm_006_edi_02'
                      }
              ]" @click="handleManage(1, record)">编辑</a>
              </template>
              <!-- 删除 -->
              <!-- <template v-if="record.statusCode === '0'">
                <a-divider v-btnPermission="'qm_006_del_03'" type="vertical"></a-divider>
                <a v-btnPermission="'qm_006_del_03'" @click="handleRemove(record)">删除</a>
              </template> -->
              <template v-if="record.statusCode === '2'">
                <a v-btnPermission="[
                      {
                        ident: 'prma_seex',
                        code: 'seex_qm_006_edi_05'
                      },
                      {
                        ident: 'prma_buco',
                        code: 'buco_qm_006_edi_05'
                      }
              ]" @click="handleOpen(record)">落实金额</a>
              </template>
              <!-- v-btnPermission="'qm_006_edi_02'" -->
              <!-- 当状态为审批中 -->
              <template v-if="record.statusCode != '0'">
                <a v-btnPermission="[
                      {
                        ident: 'prma_seex',
                        code: 'seex_qm_006_exa_06'
                      },
                      {
                        ident: 'prma_buco',
                        code: 'buco_qm_006_exa_06'
                      }
              ]" @click="$bus.$emit('showApprovalDetailsDialog', record.id)"
                  >审批详情</a
                >
              </template>
            </MoreButton>
          </span>
          <!-- 状态 -->
          <template slot="statusCode" slot-scope="text, record">
            <status-display :statusCode="record.statusCode" :statusMap="statusMap"></status-display>
          </template>
          <span slot="expandedRowRender" slot-scope="record">事实描述：{{ record.factDescription || '无' }}</span>
          <!-- 汇总 -->
          <span slot="prefix">
            <a-button v-btnPermission="[
                      {
                        ident: 'prma_seex',
                        code: 'seex_qm_006_add_01'
                      },
                      {
                        ident: 'prma_buco',
                        code: 'buco_qm_006_add_01'
                      }
              ]" class="mb12" type="primary" icon="plus" @click="handleManage(0)"
              >添加质量奖罚</a-button
            >
          </span>
          <div slot="bottom">
            <a-collapse :bordered="false" v-model="activeKey" expand-icon-position="right" class="mb12">
              <a-collapse-panel style="background: #e6f3fc; border: none" :showArrow="false">
                <template slot="header">
                  <a-row type="flex" justify="space-between" align="middle" style="width: 100%">
                    <div>
                      <a-icon style="color: #108ee9" type="exclamation-circle" />
                      <span>
                        已选择
                        <a
                          ><b>{{ countRewardAndPenalty.tableCount || 0 }}</b></a
                        >
                        项
                      </span>
                      <a-divider type="vertical"></a-divider>
                      <span>总计--</span>
                      <span
                        >罚款：<a
                          ><b>{{ countRewardAndPenalty.penalty || 0 }}</b></a
                        >元</span
                      >
                      <a-divider type="vertical"></a-divider>
                      <span
                        >落实:<a
                          ><b>{{ countRewardAndPenalty.penaltyImplementation || 0 }}</b></a
                        >元</span
                      >
                      <a-divider type="vertical"></a-divider>
                      <span
                        >奖励:<a
                          ><b>{{ countRewardAndPenalty.reward || 0 }}</b></a
                        >元</span
                      >
                      <a-divider type="vertical"></a-divider>
                      <span
                        >落实:<a
                          ><b>{{ countRewardAndPenalty.rewardImplementation || 0 }}</b></a
                        >元</span
                      >
                    </div>
                    <div>
                      <a-button :loading="loading" type="primary" @click.stop="getSummary(0)">汇总所有</a-button>
                      <a-button
                        :loading="loading"
                        :disabled="rowSelection.selectedRowKeys.length === 0"
                        type="primary"
                        @click.stop="getSummary(1)"
                        >汇总选中</a-button
                      >
                      <a class="btn_right">
                        <span>{{ activeKey.length > 0 ? '收起' : '展开' }}详细汇总信息</span>
                        <a-icon :type="activeKey.length > 0 ? 'up' : 'down'" />
                      </a>
                    </div>
                  </a-row>
                </template>
                <div>
                  <a-tabs :activeKey="args.countTableType" @change="switchSummary">
                    <a-tab-pane key="0" tab="罚款">
                    </a-tab-pane>
                    <a-tab-pane key="1" tab="奖励">
                    </a-tab-pane>
                  </a-tabs>
                  <s-table
                        ref="tableSummary"
                        tableLayout="fixed"
                        size="default"
                        bordered
                        :rowKey="(record, index) => record.id + index"
                        :scroll="{ y: 1000 }"
                        :columns="args.countTableType == '0' ? columnsSummary0 : columnsSummary1"
                        :data="loadDataSummary"
                        :showPagination="false"
                        style="background: #fff"
                      >
                        <div slot="name" slot-scope="text">
                          <ellipsis :length="30" tooltip>{{ text }}</ellipsis>
                        </div>
                      </s-table>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </div>
        </list-table>
      </a-card>
    </div>
    <dialog-reward
      ref="dialogReward"
      width="600px"
      :visible.sync="visible"
      :form="forms"
      headerTitle="落实金额"
      @confirm="submitForm"
    />
  </base-breadcrumb>
</template>

<script>
import { STable, Ellipsis } from '@/components' // 表格
import { rewardAndPenalty } from '@/api/quality/quality' // api
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import OrgTreeSelect from '@/components/OrgTreeSelect'
import dialogReward from '@/views/quality/rewardAndPenalty/rewardAndPenaltyManage/dialogReward' // 落实金额表单弹窗
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import Selector from '@/components/Select/Selector' // 通用下拉框
import InputRange from '@/components/Input/InputRange' // 项目名称
import cloneDeep from 'lodash.clonedeep' // 深拷贝
import { Collapse } from 'ant-design-vue' // ant
import StatusDisplay from '@/components/StatusDisplay'
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
import SelectProjectStatus from '@/views/quality/components/SelectProjectStatus' // 项目状态

const searchArr = [
  // 搜索框
  {
    name: '奖罚单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
    attrs: {
      isSelectableRootNode: true
    }
  },
  // {
  //   name: '分公司',
  //   type: SelectSubCompany,
  //   valueKey: 'branchCompanyId'
  // },
  // {
  //   name: '项目名称',
  //   type: SelectProject,
  //   valueKey: 'projectId'
  // },
  {
    name: '项目状态',
    type: SelectProjectStatus,
    valueKey: 'projectStatus',
  },
  {
    name: '工程类别',
    type: SelectProjectType,
    // maxTagCount: 2,
    // mode: 'multiple',
    valueKey: 'constructionTypeIds',
    showStop:false
    // currentRender(e) {
    //   return e?.length ? e.join() : e
    // }
  },
  {
    name: '编制人',
    type: 'input',
    value: 'editor'
  },
  {
    name: '奖罚目标类别',
    type: Selector,
    selectType: '10',
    valueKey: 'rewardAndPenaltyTargetCategory'
  },
  {
    name: '奖罚时间',
    type: 'dateRange',
    value: 'rewardAndPenaltyTime'
  },
  {
    name: '奖罚类别',
    valueKey: 'rewardAndPenaltyCategory',
    type: Selector,
    selectType: '9'
  },
  {
    name: '奖罚金额（元）',
    type: InputRange,
    valueKey: 'rewardAndPenaltyAmount'
  },
  {
    name: '奖罚目标名称',
    type: 'input',
    value: 'rewardAndPenaltyTargetName'
  }
]
const columns = [
  {
    title: '奖罚单位',
    ellipsis: true,
    dataIndex: 'searchQuery',
    scopedSlots: { customRender: 'searchQuery' }
  },
  {
    title: '检查类别',
    ellipsis: true,
    dataIndex: 'checkName',
  },
  {
    title: '奖罚类别',
    ellipsis: true,
    dataIndex: 'rewardAndPenaltyCategory'
  },
  {
    title: '奖罚金额（元）',
    width: '130px',
    ellipsis: true,
    dataIndex: 'rewardAndPenaltyAmount'
  },
  {
    title: '编制人',
    ellipsis: true,
    dataIndex: 'editor'
  },
  {
    title: '奖罚目标类别',
    width: '130px',
    ellipsis: true,
    dataIndex: 'rewardAndPenaltyTargetCategory'
  },
  {
    title: '奖罚目标名称',
    width: '130px',
    ellipsis: true,
    dataIndex: 'rewardAndPenaltyTargetName'
  },
  {
    title: '奖罚依据',
    width: '130px',
    ellipsis: true,
    dataIndex: 'rewardPunishmentBasis'
  },
  {
    title: '落实金额（元）',
    width: '130px',
    ellipsis: true,
    dataIndex: 'implementationAmount'
  },
  {
    title: '奖罚时间',
    width: '110px',
    ellipsis: true,
    dataIndex: 'rewardAndPenaltyTime'
  },
  {
    title: '状态',
    width: '110px',
    ellipsis: true,
    dataIndex: 'statusCode',
    scopedSlots: { customRender: 'statusCode' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '230px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
const customColumns = [
  {
    title: '序号',
    dataIndex: 'index'
  },
  {
    title: '分公司',
    dataIndex: 'branchCompanyName'
  },
  {
    title: '项目名称',
    dataIndex: 'projectName'
  },
  {
    title: '检查类别',
    ellipsis: true,
    dataIndex: 'checkName',
  },
  {
    title: '奖罚类别',
    dataIndex: 'rewardAndPenaltyCategory'
  },
  {
    title: '奖罚金额（元）',
    dataIndex: 'rewardAndPenaltyAmount'
  },
  {
    title: '编制人',
    dataIndex: 'editor'
  },
  {
    title: '奖罚目标类别',
    dataIndex: 'rewardAndPenaltyTargetCategory'
  },
  {
    title: '奖罚目标名称',
    dataIndex: 'rewardAndPenaltyTargetName'
  },
  {
    title: '奖罚依据',
    dataIndex: 'rewardPunishmentBasis'
  },
  {
    title: '落实金额（元）',
    dataIndex: 'implementationAmount'
  },
  {
    title: '奖罚时间',
    dataIndex: 'rewardAndPenaltyTime'
  },
  {
    title: '状态',
    dataIndex: 'statusName'
  }
]
const columnsSummary0 = [
  {
    title: '分公司',
    dataIndex: 'name',
    width: 200,
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '分包单位罚款',
    children: [
      {
        title: '项目',
        dataIndex: 'subUnitsPenalty.projectFines'
      },
      {
        title: '分公司',
        dataIndex: 'subUnitsPenalty.branchFines'
      },
      {
        title: '公司',
        dataIndex: 'subUnitsPenalty.companyFines'
      },
      {
        title: '合计',
        dataIndex: 'subUnitsPenalty.totalFines'
      },
    ]
  },
  {
    title: '个人罚款',
    children: [
      {
        title: '项目',
        dataIndex: 'personalPenalty.projectFines'
      },
      {
        title: '分公司',
        dataIndex: 'personalPenalty.branchFines'
      },
      {
        title: '公司',
        dataIndex: 'personalPenalty.companyFines'
      },
      {
        title: '合计',
        dataIndex: 'personalPenalty.totalFines'
      },
    ]
  },
  {
    title: '罚款总额',
    dataIndex: 'penalty'
  },
  {
    title: '分包罚款落实金额',
    dataIndex: 'subUnitsPenalty.subUnitsPenaltyImplement'
  },
  {
    title: '个人罚款落实金额',
    dataIndex: 'personalPenalty.personalImplementation'
  },
  {
    title: '落实总金额',
    dataIndex: 'penaltyImplementation'
  },
  {
    title: '分包罚款落实率',
    dataIndex: 'subUnitsPenalty.subUnitsImplRate'
  },
  {
    title: '个人罚款落实率',
    dataIndex: 'personalPenalty.personalImplRate'
  },
  {
    title: '总落实率',
    dataIndex: 'penaltyAllImplRate',
  }
]
const columnsSummary1 = [
  {
    title: '分公司',
    dataIndex: 'name',
    width: 200,
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '分包单位奖励',
    children: [
    {
        title: '项目',
        dataIndex: 'subUnitsPenalty.projectReward'
      },
      {
        title: '分公司',
        dataIndex: 'subUnitsPenalty.branchReward'
      },
      {
        title: '公司',
        dataIndex: 'subUnitsPenalty.companyReward'
      },
      {
        title: '合计',
        dataIndex: 'subUnitsPenalty.totalReward'
      },
    ]
  },
  {
    title: '个人奖励',
    children: [
      {
        title: '项目',
        dataIndex: 'personalPenalty.projectReward'
      },
      {
        title: '分公司',
        dataIndex: 'personalPenalty.branchReward'
      },
      {
        title: '公司',
        dataIndex: 'personalPenalty.companyReward'
      },
      {
        title: '合计',
        dataIndex: 'personalPenalty.totalReward'
      },
    ]
  },
  {
    title: '奖励总额',
    dataIndex: 'reward'
  },
  {
    title: '分包奖励落实金额',
    dataIndex: 'subUnitsPenalty.subUnitsRewardImplement'
  },
  {
    title: '个人奖励落实金额',
    dataIndex: 'personalPenalty.personalRewardImplementation'
  },
  {
    title: '落实总金额',
    dataIndex: 'rewardImplementation'
  },
  {
    title: '分包奖励落实率',
    dataIndex: 'subUnitsPenalty.subUnitsRewardImplRate'
  },
  {
    title: '个人奖励落实率',
    dataIndex: 'personalPenalty.personalRewardImplRate'
  },
  {
    title: '总落实率',
    dataIndex: 'rewardAllImplRate'
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    STable,
    dialogReward,
    Ellipsis,
    StatusDisplay,
    ACollapse: Collapse,
    ACollapsePanel: Collapse['Panel']
  },
  data() {
    this.columns = columns
    this.columnsSummary0 = columnsSummary0
    this.columnsSummary1 = columnsSummary1
    this.customColumns = customColumns
    this.searchArr = searchArr
    return {
      activeKey: [],
      visible: false, // 弹窗控件
      loading: false, // 汇总按钮加载控件
      statusMap: {
        0: {
          label: '待提交审批',
          color: '#FE5500'
        },
        1: {
          label: '审批中',
          color: '#00A854'
        },
        2: {
          label: '待落实',
          color: '#00A854'
        },
        3: {
          label: '审批不通过',
          color: '#FE5500'
        },
        4: {
          label: '已落实',
          color: '#FE5500'
        }
      }, // 审批状态
      rowSelection: {
        selectedRowKeys: [],
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.isChildren
          }
        }),
        onChange: (e) => {
          this.countRewardAndPenalty.tableCount = e.rows?.length
          if (e.rows.length === 0) {
            for (let index in this.countRewardAndPenalty) {
              this.countRewardAndPenalty[index] = 0
            }
          }
          this.rowSelection.selectedRowKeys = e.keys
        }
      },
      forms: {},
      isShow: false,
      queryParam: {}, // 查询参数
      countRewardAndPenalty: {
        tableCount: 0, // 总计
        penalty: 0, // 罚款
        penaltyImplementation: 0, //罚款落实
        reward: 0, // 奖励
        rewardImplementation: 0 // 奖励落实
      },
      args: {
        countTableType: '0',
        ids: [] // 表格选中集合
      },
      // 盒子高度
      boxHeight: 0,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        // 格式化参数
        let rewardAndPenaltyTime = this.queryParam.rewardAndPenaltyTime
        if (rewardAndPenaltyTime?.length > 0) {
          this.queryParam.rewardAndPenaltyTimeStart = rewardAndPenaltyTime[0].format('YYYY-MM-DD')
          this.queryParam.rewardAndPenaltyTimeEnd = rewardAndPenaltyTime[1].format('YYYY-MM-DD')
          delete this.queryParam.rewardAndPenaltyTime
        }
        let form = {}
        this.form[0] && (form.rewardAndPenaltyAmountMin = this.form[0])
        this.form[1] && (form.rewardAndPenaltyAmountMax = this.form[1])
        const requestParameters = Object.assign({}, parameter, this.queryParam, form)
        return rewardAndPenalty.postList(requestParameters).then((res) => {
          // this.$refs.table.clearSelected()
          if (res.data) {
            res.data = res.data.map(record => {
              if (record.check && record.check.checkType && record.check.checkType.name) {
                record.checkName = record.check.checkType.name
              } else {
                record.checkName = ''
              }
              return record
            })
          }
          return res
        })
      },
      // 汇总异步数据
      loadDataSummary: (parameter) => {
        let that = this
        if (!that.isInit) {
          return false
        }
        const requestParameters = Object.assign({}, parameter, that.args)
        that.loading = true
        return rewardAndPenalty
          .count(requestParameters)
          .then((res) => {
            that.loading = false
            // 深拷贝回调对象
            let datas = cloneDeep(res)
            datas.data = res.data.countRewardAndPenalties // 列表对象
            // tableCount
            Object.assign(that.countRewardAndPenalty, res.data.countRewardAndPenalty)
            return datas
          })
          .catch((res) => {
            that.loading = false
          })
      },
      isInit: false, // 汇总初始化标识
      form: ['', '']
    }
  },
  methods: {
    selectClick(e) {
      let { rows, keys } = e
      this.rowSelection.onChange(e)
      this.rowSelection.selectedRowKeys = keys
    },

    /**
     * 删除草稿
     */
    handleRemove(record) {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return rewardAndPenalty.remove({ id: record.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.search()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        }
      })
    },
    // 落实金额
    submitForm(e) {
      let that = this
      rewardAndPenalty
        .implement(e)
        .then((res) => {
          that.$refs.dialogReward.loading = false
          // if (res.data.code == 200) {
          that.$message.success('落实成功！')
          that.visible = false
          // 重置页面
          that.$refs.table.loadData()
          // } else {
          //   that.$message.warning('落实失败！')
          // }
        })
        .catch((res) => {
          that.$refs.dialogReward.loading = false
        })
    },
    // 切换汇总信息
    switchSummary(e) {
      this.args.countTableType = e
    },
    // 汇总选中
    getSummary(e) {
      let that = this
      if (!e) {
        // console.log('汇总所有')
        that.args.ids = []
        that.args = Object.assign(that.args, that.$refs.searchData.form.getFieldsValue())
      } else {
        // console.log('汇总选中')
        that.args.ids = that.rowSelection.selectedRowKeys
      }
      if (that.activeKey.length == 0) {
        that.activeKey = ['0']
      }
      that.$nextTick(() => {
        !that.isInit && (that.isInit = true)
        that.$refs.tableSummary.refresh(true)
      })
    },
    // 重置
    handleReset(e) {
      this.$set(this.form, 0, '')
      this.$set(this.form, 1, '')
    },
    // 搜索
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    // 操作栏
    handleManage(e, record) {
      let query = {
        editModel: e
      }
      if (record) {
        query.id = record.id
      }
      this.$router.push({
        name: '/quality/rewardAndPenalty/rewardAndPenaltyManage/rewardAndPenaltyManageEdit',
        query
      })
    },
    // 打开落实金额弹窗
    handleOpen(e) {
      this.forms = e
      this.visible = true
    }
  }
}
</script>
